<template>
  <div id="app">
    <router-view />
  </div>
</template>
<script>
import { mapMutations } from 'vuex';
import connectWS from '@/utils/websocket/index';
import { getUrlParam, isEndWithX, timeoutTask } from '@/utils/index';
import {
  formatGiftList,
  formatPhotoTypeList,
  formatDanmuTypeList,
  formatSuperDanmuTypeList,
  formatBapinTypeList,
  formatBapinTypeList2,
  getGameInfoByGameCode,
} from '@/utils/service';
import {
  getLiveInfo,
  getGiftList,
  getGiftList2,
  getHBKDInfo,
  getGameStatus,
  buyVipEnterEffect,
  editUserInfo,
  sendSuperDanmuGift,
} from '@/api/index/index';
import { sendSuperDanmuGiftMessage } from '@/api/chat/index';
import { getSongSheetList, orderSong } from '@/api/music/index';
import { POPUP_MODULE } from '@/assets/constant/index';

export default {
  name: 'app',
  data() {
    return {};
  },
  computed: {},
  created() {
    this.setToken(getUrlParam('token'));
    this.setLiveId(getUrlParam('liveId'));
    // 其他的webview容器
    if (isEndWithX(window.location.href, 'photoWall')) {
      this.$router.push({
        path: '/photoWall',
      });
    }
    // 获取活动信息
    getLiveInfo()
      .then((res) => {
        console.log('***活动信息***');
        console.log(res);
        this.handleLiveInfo(res);
        this.setEnterSceneInfo();
      })
      .catch((err) => {
        console.log(err);
      });

    // 获取歌曲列表
    getSongSheetList()
      .then((res) => {
        console.log('getSongSheetList:', res);
        this.setChooseSongVisible(res.isOpen);

        const mode = res.splidInfo && res.splidInfo.music_mode;
        if (typeof mode !== 'undefined') {
          this.setMusicMode(mode);
        }

        // 普通模式才用这份通用歌单
        if (mode === '0') {
          this.setSongSheetList(res.list);
        } else {
          // 歌手模式就先不填 songSheetList，等选歌手时再拉
          this.setSongSheetList([]);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  },
  mounted() {
    // 连接websocket
    connectWS();
    window.testBapin = this.testBapin;
    window.testEnterEffect = this.testEnterEffect;
  },
  methods: {
    ...mapMutations({
      setToken: 'app/setToken',
      setUserInfo: 'user/setUserInfo',
      setLiveId: 'live/setLiveId',
      setSceneType: 'live/setSceneType',
      setTitle: 'live/setTitle',
      setBackground: 'live/setBackground',
      setLoading: 'app/setLoading',
      togglePopup: 'app/togglePopup',
      setGiftList: 'live/setGiftList',
      setGiftList2: 'live/setGiftList2',
      setPhotoTypeList: 'live/setPhotoTypeList',
      setCurrentPhotoType: 'app/setCurrentPhotoType',
      setDanmuTypeList: 'live/setDanmuTypeList',
      setCurrentDanmuType: 'app/setCurrentDanmuType',
      setSuperDanmuTypeList: 'live/setSuperDanmuTypeList',
      setCurrentSuperDanmuType: 'app/setCurrentSuperDanmuType',
      setBapinTypeList: 'live/setBapinTypeList',
      setCurrentBapinType: 'app/setCurrentBapinType',
      setCurrentGiftType: 'app/setCurrentGiftType',
      setRechargeList: 'live/setRechargeList',
      setHbkdRechargeList: 'live/setHbkdRechargeList',
      setHbkdInfo: 'live/setHbkdInfo',
      setQrcodeUrl: 'live/setQrcodeUrl',
      setZyzList: 'live/setZyzList',
      setOrigin: 'app/setOrigin',
      setUseTip: 'app/setUseTip',
      setGiftSendVisible: 'app/setGiftSendVisible',
      setHbkdVisible: 'app/setHbkdVisible',
      setHeartWallPrice: 'app/setHeartWallPrice',
      setEditUserInfoPrice: 'app/setEditUserInfoPrice',
      setIsFreeSendPhoto: 'live/setIsFreeSendPhoto',
      setEmceeId: 'live/setEmceeId',
      setPhotographerWallInfo: 'app/setPhotographerWallInfo',
      setWifi: 'live/setWifi',
      setBroadContent: 'live/setBroadContent',
      setLogoPath: 'live/setLogoPath',
      setOnlineNum: 'live/setOnlineNum',
      setChooseSongVisible: 'app/setChooseSongVisible',
      setSongSheetList: 'app/setSongSheetList',
      setMusicMode: 'app/setMusicMode',
      setCurrentSingerId: 'app/setCurrentSingerId',
      setBeerJson: 'live/setBeerJson',
      setTipGiftList: 'app/setTipGiftList',
      setCanCustomizeInput: 'app/setCanCustomizeInput',
    }),
    setEnterSceneInfo() {
      // 进入场景
      const origin = getUrlParam('origin');
      // 使用提示
      const useTipFlag = getUrlParam('useTipFlag');
      if (useTipFlag) {
        this.setUseTip(true);
      }
      if (origin === 'sendGift') {
        // 发礼物
        this.togglePopup(POPUP_MODULE.giftModule.key);
      } else if (origin === 'sendBapin') {
        // 发霸屏
        this.togglePopup(POPUP_MODULE.bapinModule.key);
      } else if (origin === 'sendPhoto') {
        // 发照片
        this.togglePopup(POPUP_MODULE.photoModule.key);
      } else if (origin === 'sendDanmu') {
        // 发弹幕
        this.togglePopup(POPUP_MODULE.danmuModule.key);
      } else if (origin === 'sendDanmuHby') {
        // 红包雨等待界面发弹幕
        this.$router.push({
          path: '/hby',
        });
        timeoutTask(() => {
          this.togglePopup(POPUP_MODULE.danmuModule.key);
        }, 1000);
      } else if (origin === 'purchaseEnterEffect') {
        const tmpGiftId = localStorage.getItem('tmpGiftId');
        // 购买进场特效
        buyVipEnterEffect(tmpGiftId)
          .then((res) => {
            console.log(res);
            localStorage.removeItem('tmpGiftId');
            if (res.code === '200') {
              this.$toast.center('进场特效购买成功!');
              window.location.reload();
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else if (origin === 'editInfo') {
        const tmpEditInfo = JSON.parse(localStorage.getItem('tmpEditInfo'));
        editUserInfo(tmpEditInfo)
          .then((res) => {
            localStorage.removeItem('tmpEditInfo');
            if (res.code === '200') {
              this.$toast.center('修改成功!');
              this.setUserInfo({
                name: tmpEditInfo.wx_name,
                headImg: tmpEditInfo.avator,
                relativeType: tmpEditInfo.type,
                deskNum: tmpEditInfo.table_number,
                currentStatus: tmpEditInfo.position,
              });
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else if (origin === 'sendSuperDanmu') {
        const tmpSuperDanmuInfo = JSON.parse(localStorage.getItem('tmpSuperDanmuInfo'));
        sendSuperDanmuGift(tmpSuperDanmuInfo.superDanmuWish, tmpSuperDanmuInfo.superDanmuId)
          .then((res) => {
            localStorage.removeItem('tmpSuperDanmuInfo');
            let tmpResult = null;
            if (res.code === '200') {
              // 更新 用户余额
              this.setUserInfo({
                money: res.balance.balance,
              });
              tmpResult = sendSuperDanmuGiftMessage(tmpSuperDanmuInfo.superDanmuWish, tmpSuperDanmuInfo.superDanmuId);
            }
            return tmpResult;
          })
          .then(() => {
            this.$toast.center('发送成功!');
          })
          .catch((err) => {
            console.log(err);
          });
      } else if (origin === 'rechargeHbkd') {
        // 充值红包口袋
        this.togglePopup(POPUP_MODULE.hbkdModule.key);
      } else if (origin === 'rechargeHby') {
        // 充值红包雨
        this.togglePopup(POPUP_MODULE.sendHbModule.key);
      }
      this.setOrigin('');
    },
    handleLiveInfo(res) {
      // 设置用户信息
      this.setUserInfo({
        userId: res.user.USER_ID,
        openId: res.user.openid,
        name: res.user.wx_name,
        headImg: res.user.avator,
        money: res.money.balance,
        hbyMoney: res.money.hby_balance,
        freeSendGift: res.freeSendGift,
        miao_vip_splid: res.user.miao_vip_splid,
        miao_vip: res.user.miao_vip,
        vipLevel: res.user.vip_level,
        relativeType: res.user.type,
        currentStatus: res.user.position,
        deskNum: res.user.table_number,
        enterEffect: res.user.miao_vip_car,
      });
      // 进场动画
      if (res.user.miao_vip_car) {
        this.$createEnterEffect({
          name: res.user.wx_name,
          headImg: res.user.avator,
          enterEffectType: res.user.miao_vip_car,
        });
      } else {
        this.$createEnterEffect({
          name: res.user.wx_name,
          headImg: res.user.avator,
          enterEffectType: 'common',
        });
      }
      // 设置活动信息
      this.setSceneType(res.splid.scenario);
      this.setTitle(res.splid.theme);
      this.setBackground(res.splid.phone_piclink);
      this.setQrcodeUrl(res.splid.sp_qrurl);
      this.setGiftSendVisible(res.splid.hide_gift_switch);
      this.setHbkdVisible(res.splid.hide_hbkd_switch);
      this.setIsFreeSendPhoto(res.splid.isFreeSendPhoto);
      this.setEmceeId(res.splid.userId);
      this.setWifi(res.splid.wife_mima);
      this.setBroadContent(res.splid.bar_notice);
      this.setLogoPath(res.splid.bar_logo);
      this.setOnlineNum(res.splid.signInfo.size);
      // 设置充值列表
      this.setRechargeList(res.miaoBiList);
      this.setHbkdRechargeList(res.redBaoList);
      // 设置幸运大转盘奖项
      this.setZyzList(res.luckyNynList);
      // 设置照片墙价格
      this.setHeartWallPrice(res.heart_wall_price);
      // 设置编辑个人信息价格
      this.setEditUserInfoPrice(res.edit_user_price);
      // 设置摄影师照片墙信息
      this.setPhotographerWallInfo({
        photo_shi_switch: res.splid.photo_shi_switch,
        photo_one_price: res.photo_one_price,
      });
      // 设置啤酒大作战配置信息
      this.setBeerJson(res.splid.beerJson);
      const forbidChatFlag = res.splid && res.splid.forbid_chat;
      if (forbidChatFlag === '1') {
        this.setCanCustomizeInput(false);
      } else if (forbidChatFlag === '0') {
        this.setCanCustomizeInput(true);
      }
      // 获取游戏状态
      this.getGameState();
      // 获取礼物列表
      this.getGiftList2();
      // 获取红包口袋金额
      this.getHBKDInfo();
    },
    handleGiftInfo(res) {
      console.log('*****gift_list******');
      console.log(res.list1);
      // 礼物列表赋值
      const giftListFormat = formatGiftList(res.list1);
      this.setGiftList({
        giftList_format: giftListFormat,
        giftList: res.list1,
      });

      this.setCurrentGiftType(giftListFormat[0][0].giftId);
      // 照片类型列表赋值
      if (res.list4) {
        const photoTypeListFormat = formatPhotoTypeList(res.list4);
        this.setPhotoTypeList(photoTypeListFormat);
        this.setCurrentPhotoType(photoTypeListFormat[0].giftId);
      }
      // 霸气弹幕类型列表赋值
      const danmuTypeListFormat = formatDanmuTypeList(res.list2);
      this.setDanmuTypeList(danmuTypeListFormat);
      this.setCurrentDanmuType(danmuTypeListFormat[0].giftId);

      //  霸屏类型列表赋值
      const bapinTypeListFormat = formatBapinTypeList(res.list3);
      this.setBapinTypeList(bapinTypeListFormat);
      this.setCurrentBapinType(bapinTypeListFormat[0].giftId);
    },
    handleGiftInfo2(res) {
      console.log('*****new gift_list******');
      console.log(res);
      const tmpGiftTitleList = [res.title.list1, res.title.list5, res.title.list666];
      const tmpGiftListFormat01 = formatGiftList(res.data.list1);
      const tmpGiftListFormat02 = formatGiftList(res.data.list5);
      const tmpGiftListFormat03 = formatGiftList(res.data.list666);
      this.setGiftList2({
        giftTitleList: tmpGiftTitleList,
        giftList_format01: tmpGiftListFormat01,
        giftList_format02: tmpGiftListFormat02,
        giftList_format03: tmpGiftListFormat03,
        giftList01: res.data.list1,
        giftList02: res.data.list5,
        giftList03: res.data.list666,
      });
      this.setCurrentGiftType(tmpGiftListFormat01[0][0].giftId);

      // 照片类型列表赋值
      if (res.data.list4) {
        const photoTypeListFormat = formatPhotoTypeList(res.data.list4);
        this.setPhotoTypeList(photoTypeListFormat);
        this.setCurrentPhotoType(photoTypeListFormat[0].giftId);
      }
      // 霸气弹幕类型列表赋值
      const danmuTypeListFormat = formatDanmuTypeList(res.data.list2);
      this.setDanmuTypeList(danmuTypeListFormat);
      this.setCurrentDanmuType(danmuTypeListFormat[0].giftId);

      // 超级弹幕类型列表赋值
      const superDanmuTypeListFormat = formatSuperDanmuTypeList(res.data.list667);
      this.setSuperDanmuTypeList(superDanmuTypeListFormat);
      this.setCurrentSuperDanmuType(superDanmuTypeListFormat[0].giftId);

      //  霸屏类型列表赋值
      const bapinTypeListFormat = formatBapinTypeList2(res.data.list3);
      this.setBapinTypeList(bapinTypeListFormat);
      this.setCurrentBapinType(bapinTypeListFormat[0].giftId);

      // tip 礼物列表：后端直接提供在 list6，中间用 formatGiftList 处理后再扁平化
      const tmpTipGiftPages = formatGiftList(res.data.list6 || []);
      const tmpTipGiftList = tmpTipGiftPages.reduce((acc, page) => acc.concat(page), []);
      this.setTipGiftList(tmpTipGiftList);
    },
    getGameState() {
      getGameStatus()
        .then((res) => {
          console.log('游戏状态:', res);
          if (res.playInfo) {
            const gameBaseInfo = getGameInfoByGameCode(res.playInfo);
            this.$store.commit('game/setGameInfo', {
              currentGameCode: res.playInfo,
              enterType: gameBaseInfo.enterType,
              gameUrl: gameBaseInfo.gameUrl,
              needShake: gameBaseInfo.needShake,
            });
            if (res.status === '0' || res.status === '1') {
              // 游戏等待中
              this.$store.commit('game/setGameStatus', 1);
              // 游戏按钮出现
              if (res.playInfo !== 'sign') {
                // 游戏按钮出现(游戏不包括签到)
                this.$store.commit('app/setGameBtnVisible', true);
              }
              const specialHandleGame = ['hmPlay1', 'hmPlay6', 'hmPlay7', 'hmPlay8', 'hmPlay9', 'hmPlay11', 'hmPlay20'];
              if (specialHandleGame.indexOf(res.playInfo) > -1 && res.status === '1') {
                // 红包雨、摇一摇、数钞票、谁最牛特殊处理(0表示游戏等待、1表示游戏进行中)
                this.$store.commit('game/setGameStatus', 2);
              }
            } else if (res.status === '2') {
              this.$store.commit('game/setGameStatus', 2);
            } else if (res.status === '3') {
              this.$store.commit('game/setGameStatus', 3);
              // 游戏按钮消失
              this.$store.commit('app/setGameBtnVisible', false);
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getGiftList() {
      getGiftList()
        .then((res) => {
          console.log(res);
          this.handleGiftInfo(res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getGiftList2() {
      getGiftList2()
        .then((res) => {
          console.log(res);
          this.handleGiftInfo2(res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getHBKDInfo() {
      getHBKDInfo()
        .then((res) => {
          console.log(res);
          this.setHbkdInfo({
            remainMoney: res.money,
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    testRocket() {
      this.$createRocketDanmu({
        name: '汪元会',
        headImg: require('./assets/image/defaultHeadImg.png'),
        content: '000000000',
        rocketType: 0,
      });
      this.$createRocketDanmu({
        name: '汪元会',
        headImg: require('./assets/image/defaultHeadImg.png'),
        content: '1111111111111',
        rocketType: 1,
      });
      this.$createRocketDanmu({
        name: '汪元会',
        headImg: require('./assets/image/defaultHeadImg.png'),
        content: '222222222222',
        rocketType: 2,
      });
    },
    testBapin() {
      this.$createLoveBapin({
        name: '汪元会',
        headImg: require('./assets/image/defaultHeadImg.png'),
        content: '九分零四的几个老师交',
        bapinType: 0,
        time: 10,
      });
      this.$createLoveBapin({
        name: '汪元会',
        headImg: require('./assets/image/defaultHeadImg.png'),
        content: '九分零四的几个老师交',
        bapinType: 1,
        time: 10,
      });
      this.$createLoveBapin({
        name: '汪元会',
        headImg: require('./assets/image/defaultHeadImg.png'),
        content: '九分零四的几个老师交',
        bapinType: 2,
        time: 10,
      });
      this.$createLoveBapin({
        name: '汪元会',
        headImg: require('./assets/image/defaultHeadImg.png'),
        content: '九分零四的几个老师交',
        bapinType: 3,
        time: 10,
      });
    },
    testEnterEffect() {
      // this.$createEnterEffect({
      //   name: '汪元会',
      //   headImg: require('./assets/image/defaultHeadImg.png'),
      //   enterEffectType: 'phoenix',
      // });
      //  this.$createEnterEffect({
      //   name: '汪元会',
      //   headImg: require('./assets/image/defaultHeadImg.png'),
      //   enterEffectType: 'lion',
      // });
      this.$createEnterEffect({
        name: '汪元会',
        headImg: require('./assets/image/defaultHeadImg.png'),
        enterEffectType: 'common',
      });
      // this.$createEnterEffect({
      //   name: '汪元会',
      //   headImg: require('./assets/image/defaultHeadImg.png'),
      //   enterEffectType: 'goat',
      // });
      // this.$createEnterEffect({
      //   name: '汪元会',
      //   headImg: require('./assets/image/defaultHeadImg.png'),
      //   enterEffectType: 'bird',
      // });
      // this.$createEnterEffect({
      //   name: '汪元会',
      //   headImg: require('./assets/image/defaultHeadImg.png'),
      //   enterEffectType: 'dragon',
      // });
    },
  },
};
</script>
<style>
/* 全局样式 */
* {
  margin: 0;
  padding: 0;
}
body,
html {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
div {
  box-sizing: border-box;
}
img {
  image-rendering: -moz-crisp-edges;
  image-rendering: -o-crisp-edges;
  image-rendering: -webkit-optimize-contrast;
  image-rendering: crisp-edges;
  -ms-interpolation-mode: nearest-neighbor;
}
</style>
